package com.jt.auth.config;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class SecurityConfig  extends WebSecurityConfigurerAdapter {

    //初始化加密对象
    //此对象提供了一种不可逆的加密方式 相对于MD5方式会更加安全
    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return  new BCryptPasswordEncoder();
    }

    //用于完成用户信息的认证 判定用户身份信息的合法性
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return  super.authenticationManagerBean();
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        super.configure(http);
        //1.关闭跨域攻击
        http.csrf().disable();
        //2.放行所有资源的访问
        http.authorizeRequests().anyRequest().permitAll();
        //3.定义登陆成功 和失败的处理逻辑
        http.formLogin()
                .successHandler(successHandler())
                .failureHandler(failureHandler());
    }
    @Bean
    public AuthenticationSuccessHandler successHandler(){

        return(request,response,authentication)->{
            Map<String,Object> map =  new HashMap<>();
            map.put("state",200);
            map.put("message","login ok");
            writeJsonToClient(response,map);
        };
    }
    @Bean
    public AuthenticationFailureHandler failureHandler(){
        return (request,response,exception)->{
            Map<String,Object> map =  new HashMap<>();
            map.put("state",500);
            map.put("message","login error");
            writeJsonToClient(response,map);
        };
    }

    private void writeJsonToClient(
            HttpServletResponse response,
            Map<String, Object> map) throws IOException {

        String json = new ObjectMapper().writeValueAsString(map);
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.println(json);
        out.flush();
    }

}
